<template>
    <div class="pt-12.3rem">
        <n-carousel :current-index="audioActivate.index" effect="card"
            prev-slide-style="transform: translateX(-85%) translateZ(-300px);"
            next-slide-style="transform: translateX(-15%) translateZ(-300px);" style="height: 26rem" :show-dots="false"
            :loop="true">
            <template v-for="item in musicMap">
                <n-carousel-item :style="{ width: '60%' }">
                    <img class="carousel-img" :src="item.img" />
                </n-carousel-item>
            </template>
        </n-carousel>

        <div class="text-2.8rem text-#FFFFFF font-600 mt-5.6rem text-center">
            {{ audioActivate.name }}
        </div>
        <div class="text-1.8rem text-#FFFFFF7F font-400 mt-1.6rem text-center">
            {{ audioActivate.auther }}
        </div>

        <div class="flex items-center justify-between mt-5rem text-1.8rem text-white px-6rem">
            <div>{{ currentPlayerTime }}</div>

            <n-slider v-model:value="audioProgress" :step="0.1" :tooltip="false" @dragstart="dragstart"
                @dragend="dragend" @touchstart="dragStart" @touchend="dragEnd" class="gradient-slider mx-1rem">
                <template #thumb>
                    <SvgIcon class="w-8rem h-3.5rem relative" :style="audioProgressThumb" local-icon="music-progress" />
                </template>
            </n-slider>
            <div>{{ remainingPlayerTime }}</div>
        </div>
        <div class="flex items-center w-30rem justify-between mt-5rem pl-9rem pr-8rem w-full">
            <div @click="switchMisic('pre', true)">
                <SvgIcon class="w-1.85rem h-2rem cursor-pointer" local-icon="music-pre" />
            </div>
            <div @click="togglePlay"
                class="w-5.5rem h-5.5rem cursor-pointer bg-#FFFFFF26 rounded-full flex items-center justify-center">
                <SvgIcon class="w-4.2rem h-2.8rem text-white relative left-0.2rem" v-if="!audioHasPlayed"
                    icon="mage:play-fill" />
                <SvgIcon v-else class="w-5.5rem h-2.9rem text-white" icon="mingcute:pause-fill" />
            </div>
            <div @click="switchMisic('next', true)">
                <SvgIcon class="w-1.85rem h-2rem cursor-pointer" local-icon="music-next" />
            </div>
            <SvgIcon class="w-2.5rem h-2.5rem cursor-pointer" local-icon="music-circul" />
        </div>
    </div>
</template>

<script lang="ts" setup>
import { musicMap } from "./music";
import { emitter } from "@/utils/mitt";
import { computed, onMounted, onUnmounted, reactive, ref } from "vue";
import { touchEventData } from "@/hooks/business/eventListen/event";

import { MusicWidget, eventMusic, MusicAction } from "@/hooks/business/eventListen/musicEventListen";
import { dragStartFn, dragEndFn } from "@/hooks/business/drag";
const audioProgress = ref(0);
const audioActivate = reactive({
    index: 0,
    name: musicMap[0].name,
    auther: musicMap[0].auther,
});
const audio = ref<HTMLAudioElement | null>(null);
const audioHasPlayed = ref(false);

const audioProgressThumb = computed(() => {
    if (audioProgress.value >= 8 && audioProgress.value <= 75) {
        // 将 0-0.75 映射到 2-0
        return { left: `-${1.3 - (audioProgress.value / 75) * 2}rem` };
    } else if (audioProgress.value > 75 && audioProgress.value <= 100) {
        // 将 0.75-1 映射到 0-1
        return { left: `${(audioProgress.value / 100 - 0.75) / 0.25}rem` };
    } else {
        return {
            left: `-${1.2 - (audioProgress.value / 75) * 2}rem`,
            width: `${audioProgress.value}rem`,
        };
    }
});
// 格式化时间，将秒转换为 mm:ss 格式
function formatTime(seconds: number): string {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.floor(seconds % 60);
    return `${minutes.toString().padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;
}
// 已播放时长
const currentPlayerTime = computed(() => {
    if (audioProgress.value && audio.value) {
        return formatTime(audio.value.currentTime);
    }
    return "00:00";
});
// 剩余播放时长
const remainingPlayerTime = computed(() => {
    if (audioProgress.value && audio.value && !isNaN(audio.value.duration)) {
        const remainingSeconds = audio.value.duration - audio.value.currentTime;
        return formatTime(remainingSeconds);
    }
    return "00:00";
});
// 更新进度条值
function updateProgress() {
    if (audio.value) {
        audioProgress.value =
            (audio.value.currentTime / audio.value.duration) * 100;
    }
}
// 拖动开始事件
function dragstart() {
    if (audio.value) {
        audio.value.removeEventListener("timeupdate", updateProgress);
    }
}
// 拖动结束事件
function dragend() {
    if (audio.value) {
        audio.value.currentTime =
            (audioProgress.value / 100) * audio.value.duration;
        audio.value.addEventListener("timeupdate", updateProgress);
    }
}
// 播放/暂停控制
function togglePlay() {
    if (audio.value) {
        if (!audioHasPlayed.value) {
            eventMusic(
                MusicAction.Click,
                MusicWidget.PlayMusic,
                MusicWidget.PlayMusic,
                MusicWidget.PlayMusic,
                musicMap[audioActivate.index].name,
            );
            audio.value.play().catch((error) => {
                console.error("播放失败:", error);
            });
            audioHasPlayed.value = true;
        } else {
            eventMusic(
                MusicAction.Click,
                MusicWidget.PauseMusic,
                MusicWidget.PauseMusic,
                MusicWidget.PauseMusic,
            );
            audioHasPlayed.value = false;
            audio.value.pause();
        }
    }
}
//停止音乐
function stopMusic() {
    if (audio.value) {
        audio.value.removeEventListener("timeupdate", updateProgress);
        audio.value.pause();
        audio.value.currentTime = 0; // 重置音频到开始位置
        audioProgress.value = 0; // 重置进度条
    }
}
// 切换音乐
function switchMisic(type: "pre" | "next" = "next", isHandle?: boolean) {
    stopMusic();
    if (type == "pre") {
        if (audioActivate.index == 0) {
            audioActivate.index = musicMap.length - 1;
        } else {
            audioActivate.index -= 1;
        }
        if (isHandle) {
            eventMusic(
                MusicAction.Click,
                MusicWidget.PrevMusic,
                MusicWidget.PrevMusic,
                MusicWidget.PrevMusic,
                musicMap[audioActivate.index].name,
            );
        }
    }
    if (type == "next") {
        if (audioActivate.index == musicMap.length - 1) {
            audioActivate.index = 0;
        } else {
            audioActivate.index += 1;
        }
        if (isHandle) {
            eventMusic(
                MusicAction.Click,
                MusicWidget.NextMusic,
                MusicWidget.NextMusic,
                MusicWidget.NextMusic,
                musicMap[audioActivate.index].name,
            );
        }
    }
    playMusic();
}

function playMusic() {
    audio.value = new Audio(musicMap[audioActivate.index].url); // 替换为实际的音频文件路径
    audio.value.addEventListener("timeupdate", updateProgress);
    audio.value.addEventListener("ended", () => switchMisic("next")); // 音频播放结束时自动切换到下一首
    audioActivate.name = musicMap[audioActivate.index].name;
    audioActivate.auther = musicMap[audioActivate.index].auther;
    if (audioHasPlayed.value) {
        audio.value.play().catch((error) => {
            console.error("播放失败:", error);
        });
    }
}

function dragStart(e: TouchEvent) {
    dragStartFn(e)
}
function dragEnd(e: TouchEvent,) {
    dragEndFn(e, (data: touchEventData) => {
        if (data.type === 'swipe') {
            eventMusic(MusicAction.Swipe, MusicWidget.MusicProgress, `${MusicWidget.MusicProgress}_swipe`, MusicWidget.MusicProgress, data);
        }
    })
}


// 初始化音频
onMounted(() => {
    audio.value = new Audio(musicMap[0].url); // 替换为实际的音频文件路径
    if (audio.value) {
        audio.value.addEventListener("timeupdate", updateProgress);
        audio.value.addEventListener("ended", () => switchMisic("next")); // 音频播放结束时自动切换到下一首
    }
});
// 组件卸载时移除事件监听
onUnmounted(() => {
    if (audio.value) {
        audio.value.removeEventListener("timeupdate", updateProgress);
    }
});

emitter.on("playMusic", (obj: { id: string, fn: (name: string) => any }) => {
    stopMusic();
    audioHasPlayed.value = true;

    let index = musicMap.findIndex((item) => item.id === obj.id);
    if (index == -1) {
        index = Math.floor(Math.random() * 11);
    }
    audioActivate.index = index;
    obj.fn && obj.fn(musicMap[audioActivate.index].name);
    playMusic();
});

emitter.on("playStop", () => {
    if (audio.value) {
        audioHasPlayed.value = false;
        audio.value.pause();
    }
});

emitter.on("playNext", (fn: (name: string) => any) => {
    audioHasPlayed.value = true;
    switchMisic("next");
    if (fn) {
        fn(musicMap[audioActivate.index].name);
    }
});

emitter.on("playPre", (fn: (name: string) => any) => {
    audioHasPlayed.value = true;
    switchMisic("pre");
    if (fn) {
        fn(musicMap[audioActivate.index].name);
    }
});
</script>

<style lang="scss" scoped>
.carousel-img {
    margin: 0 auto;
    width: 26rem;
    height: 26rem;
    object-fit: cover;
    border-radius: 2rem;
}

.gradient-slider {
    :deep(.n-slider-rail) {
        background: rgba(255, 255, 255, 0.1);
    }

    :deep(.n-slider-rail__fill) {
        background: linear-gradient(270deg,
                rgba(70, 245, 239, 1) 0%,
                rgba(55, 134, 148, 0.35) 49.48%,
                rgba(33, 79, 90, 1) 100%);
        /* 设置渐变效果 */
    }
}
</style>
